package middleware

import (
	"app/internal/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
)

// 前端用户token过期时间
var SupplierUserExpireDuration = time.Hour
var SupplierUserSecretKey = []byte("supplier_token")

// 设置管理端用户token过期时间
var AdminUserExpireDuration = time.Hour
var AdminUserSecretKey = []byte("admin_token")

// 实现Supplier token中间件
func SupplierJwtTokenValid(ctx *gin.Context) {
	//获取认证头部
	auth_header := ctx.Request.Header.Get("Authorization")

	if auth_header == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    401,
			"message": "请携带token ",
		})
		ctx.Abort() //中止程序
	} else {
		auths := strings.Split(auth_header, " ")

		bearer := auths[0]
		token := auths[1]

		if len(token) == 0 || len(bearer) == 0 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    401,
				"message": "请携带正确格式的token ",
			})

			ctx.Abort() //中止程序

		} else {
			user, err := pkg.AuthToken(token, SupplierUserSecretKey)

			if err != nil {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    401,
					"message": "无效的token ",
				})

				ctx.Abort() //中止程序

			} else {
				ctx.Set("supplier_email", user.Email)
				ctx.Next()
			}
		}
	}
}

func AdminJwtTokenValid(ctx *gin.Context) {
	//获取认证头部
	auth_header := ctx.Request.Header.Get("Authorization")

	if auth_header == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    401,
			"message": "请携带token ",
		})
		ctx.Abort() //中止程序
	} else {
		auths := strings.Split(auth_header, " ")

		bearer := auths[0]
		token := auths[1]

		if len(token) == 0 || len(bearer) == 0 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    401,
				"message": "请携带正确格式的token ",
			})

			ctx.Abort() //中止程序

		} else {
			user, err := pkg.AuthToken(token, AdminUserSecretKey)

			if err != nil {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    401,
					"message": "无效的token ",
				})

				ctx.Abort() //中止程序

			} else {
				ctx.Set("admin_email", user.Email)
				ctx.Next()
			}
		}
	}
}
